package cn.edu.swufe.stu2025.finalwork;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.edu.swufe.stu2025.finalwork.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    final private String TAG ="MainActivity";
    private ActivityResultLauncher<Intent> editNoteLauncher;

    @SuppressLint("NonConstantResourceId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        Log.i(TAG, "主页启动");

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //创建列表中元素
        List<note> notes = new ArrayList<>();
        for (int i=1 ; i<11;i++)
         notes.add(new note("title" + i, "content" + i));

        //添加适配器
        noteAdapter adapter = new noteAdapter(notes);
        recyclerView.setAdapter(adapter);
        // 多选状态下显示删除按钮
        Button deleteButton = findViewById(R.id.delete_button);
        adapter.setMultiSelectListener(enabled -> {
            if (enabled) {
                deleteButton.setVisibility(View.VISIBLE);
            } else {
                deleteButton.setVisibility(View.INVISIBLE);
            }
        });
        recyclerView.setAdapter(adapter);

// 删除按钮点击事件
        deleteButton.setOnClickListener(v -> {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("确认删除")
                    .setMessage("确定要删除选中的笔记吗？")
                    .setPositiveButton("取消", (dialog, which) -> dialog.dismiss())
                    .setNegativeButton("删除", (dialog, which) -> {
                        adapter.deleteSelectedNotes();
                    })
                    .show();
        });
        //列表点击事件
        recyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(
                        this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
                        public void onItemClick(View view, int position) { //单击列表中的元素，编辑文字
                            if (adapter.isMultiSelectMode()) {
                                adapter.toggleSelection(position); // 多选时单击切换选中
                            } else {
                                Log.i(TAG, "onItemClick: 单击列表");
                                note editNote = notes.get(position);
                                Intent intent = new Intent(MainActivity.this, EditNoteActivity.class);
                                intent.putExtra("title", editNote.getTitle());
                                intent.putExtra("content", editNote.getContent());
                                intent.putExtra("position", position);
                                editNoteLauncher.launch(intent);
                            }//传递数据到edit
                        }

                        //长按删除（记得添加一个确认删除的对话框）
                        public void onLongItemClick(View view, int position) {
                            Log.i(TAG, "onLongItemClick: 长按 item"+position);
                            adapter.toggleSelection(position);

                        }
                }));//recyclerView.addOnItemTouchListener结束


        //添加笔记
        Button addItem = findViewById(R.id.add_item);
        addItem.setOnClickListener(v->{
            Log.i(TAG, "onCreate: 添加笔记");
            note emptyNote = new note("","");
            notes.add(emptyNote);
            int position = notes.size()-1;
            adapter.notifyItemInserted(position);

            //打开编辑器
            Intent intent = new Intent(MainActivity.this,EditNoteActivity.class);
            intent.putExtra("title", "");
            intent.putExtra("content", "");
            intent.putExtra("position", position);
            editNoteLauncher.launch(intent);
        });//addItem.setOnClickListener

        // 导航栏切换页面
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            if (item.getItemId() == R.id.nav_notes) {
                selectedFragment = new NotesFragment();
            } else if (item.getItemId() == R.id.nav_backlog) {
                selectedFragment = new BacklogFragment();
            }
            if (selectedFragment != null) {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.fragment_container, selectedFragment)
                        .commit();
                return true;
            }
            return false;
        });

        //打开编辑页面
        editNoteLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    Log.i(TAG, "onCreate: 编辑列表");
                    /*if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        //从result中获取数据
                        Intent data = result.getData();
                        int newPositon = data.getIntExtra("position", -12345);
                        String newTitle = data.getStringExtra("title");
                        String newContent = data.getStringExtra("content");

                        if (newPositon != -1) {
                            notes.get(newPositon).setTitle(newTitle);
                            notes.get(newPositon).setContent(newContent);
                            adapter.notifyItemChanged(newPositon);
                        }
                    }*/

                    if (result.getResultCode()==RESULT_OK && result.getData() !=null){
                        Intent data = result.getData();
                        int newPosition = data.getIntExtra("position",-1);
                        String newTitle = data.getStringExtra("title");
                        String newContent = data.getStringExtra("content");

                        Log.i(TAG, "添加元素");
                        if(newPosition>=0 && newPosition<notes.size()){
                            if (newTitle.isEmpty() && newContent.isEmpty()){
                                notes.remove(newPosition);
                                adapter.notifyItemRemoved(newPosition);
                                adapter.notifyDataSetChanged();
                            }
                            else{
                                if(newTitle.isEmpty())  newTitle = "默认标题";
                                if (newContent.isEmpty()) newContent = "无内容";
                                notes.get(newPosition).setTitle(newTitle);
                                notes.get(newPosition).setContent(newContent);
                                adapter.notifyItemChanged(newPosition);
                            }
                        }
                    }
                }
        );//editNoteLauncher

    }
}